import axios from 'axios'
import store from '@/store'
import router from '@/router'
// import { MessageBox, Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // 如果token存在 注入token
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.dir(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器
service.interceptors.response.use(

  response => {
    // 后端返回数据 依据 success 值 判断是否返回成功  而不是状态码
    const { success, data, message } = response.data
    if (success) {
      return data
    }
    return Promise.reject(message)
  },
  error => {
    // console.dir(error)
    if (error.response.status === 401) {
      store.commit('user/removeInfo')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
